package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.service.UserService;
import com.itheima.utils.MyConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.SQLException;

@Service("userService")
public class UserServiceImpl implements UserService {

    //注入userDao
    @Autowired
    private UserDao userDao;

    //注入数据源  目的是获取连接
    @Autowired
    private MyConnection myConnection;

    @Override
    public void transfer(String outName, String inName, int money) throws SQLException {

        System.out.println("转账开始了");

        //获取连接并关闭自动提交事务
        myConnection.getConnection();


        try {
            //执行业务逻辑
            userDao.out(outName,money);

            //模拟死机的情况
            //int i = 1/0;

            userDao.in(inName,money);

            //提交并关闭事务
            myConnection.commitAndClose();

        } catch (Exception e) {
            e.printStackTrace();
            //如果出现异常  那么就回滚事务
            myConnection.rollbackAndClose();
        }


    }
}
